from paddleocr import PaddleOCR
import numpy as np
import cv2
#多文本检测和筛选
class MultiTextDetector:
    def __init__(self, use_psenet=False, use_angle_cls=True, lang='ch'):
        self.det_algorithm = 'PSENet' if use_psenet else 'DB'
        self.ocr = PaddleOCR(
            use_angle_cls=use_angle_cls,
            det_algorithm=self.det_algorithm,
            lang=lang,
            rec=True,
            cls=True
        )
#所有检测到的文字框和对应的置信度，方便后续进一步处理
    def detect(self, image):
        results = self.ocr.ocr(image, cls=True)
        print("OCR原始结果:", results)

        if not results:
            return []

        boxes = []
        for page in results:
            for line in page:
                print("单条结果:", line)
                if len(line) < 2:
                    continue
                box_coords = line[0]
                rec_res = line[1]

                score = 0.0
                if isinstance(rec_res, (list, tuple)) and len(rec_res) == 2:
                    try:
                        score = float(rec_res[1])
                    except (TypeError, ValueError):
                        score = 0.0
                else:
                    score = 0.0

                if not (isinstance(box_coords, list) and len(box_coords) == 4):
                    continue
                try:
                    points = [[float(pt[0]), float(pt[1])] for pt in box_coords]
                except Exception:
                    continue

                boxes.append({'box': points, 'score': score})

        boxes.sort(key=lambda x: (min(pt[1] for pt in x['box']), min(pt[0] for pt in x['box'])))
        return boxes
#过滤掉不符合要求的文字框
    def filter_boxes(self, boxes, min_score=0.5, min_size=10):
        filtered = []
        for b in boxes:
            score = b['score']
            box = b['box']
            width = np.linalg.norm(np.array(box[0]) - np.array(box[1]))
            height = np.linalg.norm(np.array(box[1]) - np.array(box[2]))

            if score >= min_score and width > min_size and height > min_size:
                filtered.append(b)
        return filtered


